<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

</body>

</html>
<script>
    (function () {
        function Observer() {
            this.obj = {};
            this.on = function (type, handler) {//订阅消息
                this.obj[type] = this.obj[type] || [];
                this.obj[type].push(handler);
            }
            this.emit = function (type, msg) {//发布消息
                // if( this.obj[type] ){ //做个判断,防止this.obj[type]获取不到而报错.
                //     this.obj[type].forEach((item)=>{
                //         item(msg);
                //     })
                // }
                // 上面的if判断可以简化为 && 与表达式
                this.obj[type] &&
                    this.obj[type].forEach((item) => { //遍历并调用每个回调函数
                        item(msg);
                    })
            }
        }
        window.Observer = Observer;//暴露函数到外面
    })()
    //实例化对象
    var t = new Observer();
    //订阅消息
    t.on('lijiaqi', function (msg) {

    })
</script>